package com.news.dao;

import com.news.model.User;
import com.news.utils.JDBCUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDao {
    private JdbcTemplate jdbcTemplate = null;
    String sql = null;
    
    public UserDao() {
        jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
    }

    // 根据账号密码查询用户
    public User login(String username, String password) {
        try {
            sql = "select * from tb_admin where username=? and password=?";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 添加用户
    public boolean addUser(User user) {
        try {
            sql = "insert into tb_admin(username, password, realname, email, admin) values(?,?,?,?,?)";
            int rows = jdbcTemplate.update(sql, 
                user.getUsername(),
                user.getPassword(),
                user.getRealname(),
                user.getEmail(),
                user.getAdmin()
            );
            return rows > 0;
        } catch (DuplicateKeyException e) {
            // 用户名或邮箱重复
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 更新用户信息
    public boolean updateUser(User user) {
        try {
            sql = "update tb_admin set username=?, password=?, realname=?, email=?, admin=? where user_id=?";
            int rows = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getRealname(),
                user.getEmail(),
                user.getAdmin(),
                user.getUser_id()
            );
            return rows > 0;
        } catch (DuplicateKeyException e) {
            // 用户名或邮箱重复
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 删除用户
    public boolean deleteUser(Integer userId) {
        try {
            sql = "delete from tb_admin where user_id=?";
            int rows = jdbcTemplate.update(sql, userId);
            return rows > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 根据用户ID查询用户
    public User findById(Integer userId) {
        try {
            sql = "select * from tb_admin where user_id=?";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 查询所有用户
    public List<User> findAll() {
        try {
            sql = "select * from tb_admin";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 检查用户名是否存在
    public boolean isUsernameExists(String username) {
        try {
            sql = "select count(*) from tb_admin where username=?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, username);
            return count > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 检查邮箱是否存在
    public boolean isEmailExists(String email) {
        try {
            sql = "select count(*) from tb_admin where email=?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, email);
            return count > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 根据用户名查询用户
    public User findByUsername(String username) {
        try {
            sql = "select * from tb_admin where username=?";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public int getUserCount(String keyword) {
        try {
            String sql = "SELECT COUNT(*) FROM tb_admin";
            if (keyword != null && !keyword.trim().isEmpty()) {
                sql += " WHERE username LIKE ? OR realname LIKE ?";
                String pattern = "%" + keyword.trim() + "%";
                return jdbcTemplate.queryForObject(sql, Integer.class, pattern, pattern);
            }
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public List<User> getUsersByPage(int offset, int pageSize, String keyword) {
        try {
            String sql = "SELECT * FROM tb_admin";
            if (keyword != null && !keyword.trim().isEmpty()) {
                sql += " WHERE username LIKE ? OR realname LIKE ?";
                sql += " ORDER BY user_id LIMIT ?, ?";
                String pattern = "%" + keyword.trim() + "%";
                return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), 
                    pattern, pattern, offset, pageSize);
            }
            sql += " ORDER BY user_id LIMIT ?, ?";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), 
                offset, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
